package org.example.apply.utils;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 客户端工具类
 */
public class WebUtils
{
    /**
     * 获取request
     */
    public static HttpServletRequest getRequest()
    {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse()
    {
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取session
     */
    public static HttpSession getSession()
    {
        return getRequest().getSession();
    }

    public static ServletRequestAttributes getRequestAttributes()
    {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string 待渲染的字符串
     * @return null
     */
    public static String renderString(HttpServletResponse response, String string)
    {
        try
        {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    public static  <T> T getLoginUser(Class<T> cls) {
        String token = WebUtils.getRequest().getHeader("token");
        JWT jwt = JWT.of(token).setKey("li".getBytes());
        String loginUserStr = jwt.getPayload("loginUser").toString();
        T t = JSONUtil.toBean(loginUserStr,cls);
        System.out.println(t);
        return t;
    }
   /* public static <T> T getLoginInfo(Class<T> cls){
        String token = WebUtils.getRequest().getHeader("token");
        String loginUser = JwtUtils.getSubject(token);
        return JSON.parseObject(loginUser, cls);
    }*/

}


